﻿
var dateFormat = 'd MM yy';
var maxPeople = 12;

var insta;

function ORonSelect(datetext, inst, element, callback) {
    var date = inst.input.datepicker('getDate');
    if (callback)
        callback(date);
    ORSetDates(date, element);
    $('#departure-date').datepicker('refresh');
    $('#arrival-date').datepicker('refresh');
    ORCHeckDatesAvalible();
}

function ORCHeckDatesAvalible() {
    if (apartmentTypeId == 0) return;
    if (dates['arrival'] == null) return;
    var startDate = new Date(dates['arrival'].getFullYear(), dates['arrival'].getMonth(), dates['arrival'].getDate());
    var avalible = true;
    while (startDate < dates['departure']) {
        var d = startDate.getDate();
        var m = startDate.getMonth() + 1;
        var y = startDate.getFullYear();
        var k = y + '-';
        if (m < 10) k += '0';
        k += m;
        if (avalibleDays[k]) {
            if (avalibleDays[k][d].Type != 0) {
                avalible = false;
                break;
            }

        } else {
            initializeAvalibleDaysForMonth(y, m, k, ORCHeckDatesAvalible);
            return;
        }
        startDate.setDate(startDate.getDate() + 1);
    }
    if (!avalible) {
        $('.reservation-box a[id$=lnkSubmit]').addClass('disabled-button').attr('disabled', 'disabled');
    } else {
        $('.reservation-box a[id$=lnkSubmit]').removeClass('disabled-button').removeAttr('disabled');
    }
}

var dates = new Array();

function ORSetDates(date, element) {
    if (date) {
        dates[element] = date;
        $('.or-' + element + '-date-text').text($.datepicker.formatDate(dateFormat, date));
        $('#' + element + 'Date').val($.datepicker.formatDate('dd.mm.yy', date));
    } else {
        dates[element] = null;
        $('.or-' + element + '-date-text').text('wybierz datę');
        $('#' + element + 'Date').val('');
    }
}

function ORArrivalChange(newDate) {
    if ($('#departure-date').datepicker('getDate') <= newDate) {
        var dnd = new Date(newDate.getFullYear(), newDate.getMonth(), newDate.getDate() + 1);

        $('#departure-date').datepicker('setDate', dnd);
        ORSetDates(dnd, 'departure');
    }
    $('#departure-date').datepicker('option', 'minDate', new Date(newDate.getFullYear(), newDate.getMonth(), newDate.getDate() + 1));
}


function ORDepartureChange(newDate) {
    if (dates['arrival'] == null || dates['arrival'] >= newDate) {
        var dnd = new Date(newDate.getFullYear(), newDate.getMonth(), newDate.getDate() - 1);
        $('#arrival-date').datepicker('setDate', dnd);
        ORSetDates(dnd, 'arrival');
    }
}

//function ORBeforeDisplayDay(date) {
//    if (date >= dates['arrival'] && date <= dates['departure'])
//        return [true, 'ui-state-checkeddate', 'Zakres od ' + $.datepicker.formatDate(dateFormat, dates['arrival']) + ' do ' + $.datepicker.formatDate(dateFormat, dates['departure'])];
//    else return [true, '', , 'Zakres od ' + $.datepicker.formatDate(dateFormat, dates['arrival']) + ' do ' + $.datepicker.formatDate(dateFormat, dates['departure'])];
//}

var apartmentTypeId = 0;

$(function () {

    var crnDate = new Date();
    crnDate = new Date(crnDate.getFullYear(), crnDate.getMonth(), crnDate.getDate());

    apartmentTypeId = parseInt($('#onlineReservation_ApartmentId').val());
    if (!apartmentTypeId) apartmentTypeId = 0;

    dates['arrival'] = $('#arrivalDate').val() ? $.datepicker.parseDate('dd.mm.yy', $('#arrivalDate').val()) : null;
    dates['departure'] = $('#departureDate').val() ? $.datepicker.parseDate('dd.mm.yy', $('#departureDate').val()) : null;

    $('#arrival-date').datepicker({
        dateFormat: dateFormat,
        defaultDate: dates['arrival'],
        minDate: crnDate,
        onSelect: function (datetext, inst) {
            ORonSelect(datetext, inst, 'arrival', ORArrivalChange);
        },
        beforeShowDay: ORBeforeDisplayDay
    });
    if (dates['arrival']) {
        $('#arrival-date').datepicker('setDate', dates['arrival']);
        ORSetDates($('#arrival-date').datepicker('getDate'), 'arrival');
    }


    $('#departure-date').datepicker({
        dateFormat: dateFormat,
        defaultDate: dates['departure'],
        minDate: new Date(crnDate.getFullYear(), crnDate.getMonth(), crnDate.getDate() + 1),
        onSelect: function (datetext, inst) { ORonSelect(datetext, inst, 'departure', ORDepartureChange); },
        beforeShowDay: ORBeforeDisplayDay
    });
    if (dates['departure']) {
        $('#departure-date').datepicker('setDate', dates['departure']);
        ORSetDates($('#departure-date').datepicker('getDate'), 'departure');
    }

    $('.or-calculate').css('cursor', 'pointer').click(function () {
        $('input[name=submitReservation]').val('1');
        $('form:eq(0)').submit();
    });

    if (apartmentTypeId > 0) {
        $('.reservation-box a[id$=lnkSubmit]').mouseenter(function () {
            if ($(this).hasClass('disabled-button')) {
                $('.unavalible-apartment').fadeIn();
            }
        }).mouseleave(function () {
            $('.unavalible-apartment').fadeOut();
        }).click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            if ($(this).hasClass('disabled-button')) {
                return;
            }
            $('#avalible-status').show();
            $('.avalible-status iframe')[0].contentWindow.LoadState(
                $('#arrivalDate').val(),
                $('#departureDate').val(),
                apartmentTypeId,
                $('select[id$=_ddlPeoplesCount]').val()
            );
            $('.avalible-status iframe')[0].contentWindow.afterShow();
        });

        ORCHeckDatesAvalible();
    }

});

var avalibleDays = new Array();
var initializedAvalibleDays = new Array();

function ORBeforeDisplayDay(date, calendar) {

    if (!calendar)
        calendar = $(this).attr('id').replace('-date', '');

    var avalible = true;
    var cssClass = '';
    var tooltip = '';

    if (date >= dates['arrival'] && date <= dates['departure']) {
        cssClass = 'ui-state-checkeddate';
        var tooltip = 'Zakres od ' + $.datepicker.formatDate(dateFormat, dates['arrival']) + ' do ' + $.datepicker.formatDate(dateFormat, dates['departure']);

    }

    //if (calendar == 'departure') { // przesunięcie na dacie wyjazdu dostępności o jeden dzień, ponieważ rezerwacja kończy się następnego dnia
    //    date.setDate(date.getDate() + 1);
    //}

    if (apartmentTypeId > 0) {
        var checkDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - ((calendar == 'departure') ? 1 : 0));

        var d = checkDate.getDate();
        var m = checkDate.getMonth() + 1;
        var y = checkDate.getFullYear();
        var k = y + '-';
        if (m < 10) k += '0';
        k += m;
        if (avalibleDays[k]) {

            avalible = avalible && avalibleDays[k][d].Type == 0;
            if (!avalible && cssClass == 'ui-state-checkeddate') {
                if (calendar == 'arrival') {
                    var forDeparture = ORBeforeDisplayDay(checkDate, 'departure');
                    if (!forDeparture[0]) {
                        cssClass = 'ui-state-checkedwrongdate';
                        tooltip = 'W tym dniu nie możesz dokonać rezerwacji, ponieważ apartament jest zajęty!';
                    }
                }
            }
        } else {
            var code = 'initializeAvalibleDaysForMonth(' + y + ', ' + m + ', \'' + k + '\', ORRefreshCalendars);';
            window.setTimeout(code, d * 100);
        }
    }

    return [
        avalible,
        cssClass,
        tooltip
    ];
}

function initializeAvalibleDaysForMonthPush(key, callback) {
    if (!callback) return;
    for (var xc = 0; xc < initializedAvalibleDays[key].length; xc++)
        if (initializedAvalibleDays[key][xc] == callback) return;
    initializedAvalibleDays[key].push(callback);
}

var lock_initializeAvalibleDaysForMonth = false;

function initializeAvalibleDaysForMonth(year, month, key, callback, forceCall) {

    if (apartmentTypeId == 0) return;

    if (avalibleDays[key]) {
        callback();
        return;
    }

    if (!forceCall && initializedAvalibleDays[key]) {
        initializeAvalibleDaysForMonthPush(key, callback);
        return;
    }
    initializedAvalibleDays[key] = new Array();
    initializeAvalibleDaysForMonthPush(key, callback);

    $('.loading-avalibles').show();

    if (lock_initializeAvalibleDaysForMonth) {
        var code = 'initializeAvalibleDaysForMonth(' + year + ', ' + month + ', \'' + key + '\', null, true);';
        window.setTimeout(code, 1000);
        return;
    }
    lock_initializeAvalibleDaysForMonth = true;
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: '/Handlers/CalendarHandler.asmx/GetDaysByGroup',
        data: "{'month':" + month + ",'year':" + year + ", 'groupId': " + apartmentTypeId + "}",
        dataType: "json",
        success: function (x) {
            lock_initializeAvalibleDaysForMonth = false;
            var dd = new Array();
            for (var xd = 0; xd < x['d']['Days'].length; xd++) {
                var d = x['d']['Days'][xd];
                dd[d.Day] = d;
            }
            avalibleDays[key] = dd;
            for (var xc = 0; xc < initializedAvalibleDays[key].length; xc++) {
                initializedAvalibleDays[key][xc]();
            }
            delete initializedAvalibleDays[key];
            if (initializedAvalibleDays.length == 0)
                $('.loading-avalibles').hide();

        }
    });
}

function ORRefreshCalendars() {
    $('#arrival-date').datepicker('refresh');
    $('#departure-date').datepicker('refresh');
}
